package org.sagemath.commandline;

import java.util.LinkedList;

import org.sagemath.singlecellserver.CommandOutput;
import org.sagemath.singlecellserver.CommandReply;
import org.sagemath.singlecellserver.Interact;
import org.sagemath.singlecellserver.SageSingleCell;
import org.sagemath.singlecellserver.SageSingleCell.OnSageListener;

public class Testcase implements OnSageListener {

	SageSingleCell server;
	String command;
	boolean finished = false;
	
	public static class Interaction {
		String control;
		Object value;
	}
	LinkedList<Interaction> interacts = new LinkedList<Interaction>();
	
	public Testcase(SageSingleCell server, String command) {
		this.server = server;
		this.command = command;
	}
	
	public Testcase addInteract(String control, Object value) {
		Interaction i = new Interaction();
		i.control = control;
		i.value = value;
		interacts.add(i);
		return this;
	}
	
	public void run() {
		server.query(command);
		while (!finished) {
			try {
				Thread.sleep(200 * 1000);
			} catch (InterruptedException e) {
				System.out.println("Testcase interrupted: "+e.getLocalizedMessage());
			}
		}
	}
	
	Interact interact;
	
	@Override
	public void onSageOutputListener(CommandOutput output) {
		System.out.println("SageOutput");
		System.out.println(output.toLongString());
		System.out.println("\n");
		System.out.flush();
		if (interact == null || interacts.isEmpty()) return;
		Interaction i = interacts.pop();
		server.interact(interact, i.control, i.value);

		if (interact == null || interacts.isEmpty()) return;
		i = interacts.pop();
		server.interact(interact, i.control, i.value);
	}

	@Override
	public void onSageAdditionalOutputListener(CommandOutput output) {
		System.out.println("SageAdditionalOutput");
		System.out.println(output.toLongString());
		System.out.println("\n");
		System.out.flush();
	}

	@Override
	public void onSageInteractListener(Interact interact) {
		this.interact = interact;
		System.out.println("SageInteract");
		System.out.println(interact.toLongString());
		System.out.println("\n");
		System.out.flush();
	}

	@Override
	public void onSageFinishedListener(CommandReply reason) {
		System.out.println("SageFinished");
		System.out.println(reason.toLongString());
		System.out.println("\n");
		System.out.flush();
		finished = true;
	}		

}
